﻿#region Namespaces

using System.IO;

using Vibstudio.X4NET.IO.Path;

using Ionic.Zip;

#endregion

namespace Vibstudio.X4NET.IO.Compression
{
    public static class CompressionExtensions
    {
        public static byte[] Compress(this byte[] bytes, string entryName)
        {
            using (MemoryStream inputStream = new MemoryStream(bytes))
            {
                using (ZipFile zip = new ZipFile())
                {
                    zip.AddEntry(entryName, inputStream);

                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        zip.Save(outputStream);
                        return outputStream.ToArray();
                    }
                }
            }
        }

        public static byte[] Compress(this FilePath filePath)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (ZipFile zip = new ZipFile())
                {
                    zip.AddFile(filePath.Path, string.Empty);
                    zip.Save(stream);
                }

                return stream.ToArray();
            }
        }

        public static byte[] Decompress(this byte[] bytes)
        {
            using (MemoryStream inputStream = new MemoryStream(bytes))
            {
                using (ZipFile zip = ZipFile.Read(inputStream))
                {
                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        zip[0].Extract(outputStream);
                        outputStream.Seek(0, SeekOrigin.Begin);

                        return outputStream.ToArray();
                    }
                }
            }
        }
    }
}